﻿#include "pch.h"
#include "CHorizontalMenuWnd.h"
#include "MainFrm.h"

IMPLEMENT_DYNAMIC(CHorizontalMenuWnd, CWnd)

CHorizontalMenuWnd::CHorizontalMenuWnd() : m_pParentWnd(nullptr) {
	// 创建字体
	if (!m_font.CreatePointFont(100, _T("Arial"))) {
		AfxMessageBox(_T("Failed to create font!"));
	}
}

CHorizontalMenuWnd::~CHorizontalMenuWnd() {
}

BOOL CHorizontalMenuWnd::Create(CWnd* pParentWnd) {
	m_pParentWnd = pParentWnd;
	LPCTSTR lpszClassName = AfxRegisterWndClass(0, LoadCursor(NULL, IDC_ARROW), (HBRUSH)(COLOR_BTNFACE + 1));
	return CWnd::CreateEx(WS_EX_TOPMOST | WS_EX_NOACTIVATE, lpszClassName, _T(""), WS_POPUP | WS_VISIBLE, 0, 0, 0, 0, pParentWnd->GetSafeHwnd(), NULL);
}

void CHorizontalMenuWnd::ShowMenu(CPoint point) {
	// 转换 point 为屏幕坐标
	ClientToScreen(&point);

	// 计算窗口大小
	CClientDC dc(this);
	dc.SelectObject(&m_font);
	CSize size(0, 0);

	for (const auto& item : m_menuItems) {
		CSize textSize = dc.GetTextExtent(item.first);
		size.cx += textSize.cx + 20;
		size.cy = max(size.cy, textSize.cy + 10);
	}

	// 显示窗口，相对于父窗口客户区的坐标
	SetWindowPos(&wndTopMost, point.x, point.y, size.cx, size.cy, SWP_SHOWWINDOW | SWP_NOACTIVATE);

	// 强制重绘窗口
	Invalidate();
	UpdateWindow();
}

void CHorizontalMenuWnd::SetMenuItems(const std::vector<std::pair<CString, UINT>>& menuItems) {
	m_menuItems = menuItems;
}

void CHorizontalMenuWnd::OnPaint() {
	CPaintDC dc(this); // device context for painting
	CFont* pOldFont = dc.SelectObject(&m_font);

	dc.SetBkMode(TRANSPARENT);

	CRect rect;
	GetClientRect(&rect);

	int x = 0;
	for (const auto& item : m_menuItems) {
		CSize textSize = dc.GetTextExtent(item.first);
		CRect itemRect(x, 0, x + textSize.cx + 20, rect.Height());

		dc.FillSolidRect(itemRect, GetSysColor(COLOR_MENU));

		dc.DrawText(item.first, &itemRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE);

		x += textSize.cx + 20;
	}

	dc.SelectObject(pOldFont);
}

void CHorizontalMenuWnd::OnLButtonUp(UINT nFlags, CPoint point) {
	int x = 0;
	for (const auto& item : m_menuItems) {
		CSize textSize = GetDC()->GetTextExtent(item.first);
		CRect itemRect(x, 0, x + textSize.cx + 20, 30);

		if (itemRect.PtInRect(point)) {
			if (m_pParentWnd) {
				m_pParentWnd->SendMessage(WM_COMMAND, item.second);
			}
			break;
		}
		x += textSize.cx + 20;
	}

	ReleaseCapture();

	if (m_menuItems.size() != 0 && IsDynamicChecked()) {
		DestroyWindow();
	}
}

void CHorizontalMenuWnd::OnKillFocus(CWnd* pNewWnd) {
	CWnd::OnKillFocus(pNewWnd);
	ReleaseCapture();
	//if (IsDynamicChecked()) {
	//	DestroyWindow();
	//}
}

BOOL CHorizontalMenuWnd::IsDynamicChecked() {
	CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd();
	if (pMainFrame) {
		return pMainFrame->IsDynamicChecked();
	}
	return FALSE;
}

BOOL CHorizontalMenuWnd::IsStaticChecked() {
	CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd();
	if (pMainFrame) {
		return pMainFrame->IsStaticChecked();
	}
	return FALSE;
}

BEGIN_MESSAGE_MAP(CHorizontalMenuWnd, CWnd)
	ON_WM_PAINT()
	ON_WM_LBUTTONUP()
	ON_WM_KILLFOCUS()
END_MESSAGE_MAP()